import clsx from "clsx";
import Link from "next/link";
import { useContext } from "react";
import { useRouter } from "next/router";
import { GetServerSideProps } from "next";

import { Context } from "../../libs/context";
import useGet from "../../utils/hooks/useGet";
import type { ListItem } from "../../types/http";
import NovelItem from "../../components/NovelItem";

import styles from "../../styles/genre.module.scss";
import { get } from "../../utils/http";

const Genre = () => {
  const { query } = useRouter();
  const { data } = useGet<ListItem[]>(
    query.genre ? `/api/genre/${query.genre}` : "/api/list"
  );
  const store = useContext(Context);

  return (
    <main className="container">
      <h2 className="novel-title">Genres</h2>
      <div className={styles.genres}>
        <Link
          href="/novels"
          title="All novels"
          className={clsx(styles.genre, {
            [styles.current]: !query.genre,
          })}
        >
          All
        </Link>
        {store.genre.map((item) => (
          <Link
            href={`/novels/${item.uri}`}
            key={item.uri}
            title={item.name}
            className={clsx(styles.genre, {
              [styles.current]: query.genre === item.uri,
            })}
          >
            {item.name}
          </Link>
        ))}
      </div>
      <h2 className="novel-title">List</h2>
      <ul className="novel-list">
        {(data?.data || []).map((item) => (
          <NovelItem
            key={item.uri}
            slug={item.uri}
            img={item.img}
            name={item.name}
          />
        ))}
      </ul>
    </main>
  );
};

export const getServerSideProps: GetServerSideProps<
  { fallback: { [key: string]: any } },
  { genre: string }
> = async ({ params }) => {
  const key = params?.genre ? `/api/genre/${params.genre}` : `/api/list`;
  const data = await get(key);

  return {
    props: {
      fallback: {
        [key]: data,
      },
    },
  };
};

export default Genre;
